import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { ArrowLeft, Download, Settings as SettingsIcon, Save, RefreshCw } from "lucide-react";

interface SettingsConfig {
  similarityThreshold: number;
  defaultAnalysisPeriod: number;
  chartTheme: 'light' | 'dark';
  autoRefresh: boolean;
  refreshInterval: number;
  exportFormat: 'csv' | 'json' | 'excel';
  dataRetention: number;
}

const defaultSettings: SettingsConfig = {
  similarityThreshold: 70,
  defaultAnalysisPeriod: 30,
  chartTheme: 'light',
  autoRefresh: false,
  refreshInterval: 60,
  exportFormat: 'csv',
  dataRetention: 365
};

export default function Settings() {
  const navigate = useNavigate();
  const [settings, setSettings] = useState<SettingsConfig>(() => {
    const saved = localStorage.getItem('stockAnalysisSettings');
    return saved ? JSON.parse(saved) : defaultSettings;
  });
  const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved'>('idle');

  const handleSettingChange = <K extends keyof SettingsConfig>(
    key: K,
    value: SettingsConfig[K]
  ) => {
    setSettings(prev => ({ ...prev, [key]: value }));
  };

  const handleSave = () => {
    setSaveStatus('saving');
    
    setTimeout(() => {
      localStorage.setItem('stockAnalysisSettings', JSON.stringify(settings));
      setSaveStatus('saved');
      
      setTimeout(() => {
        setSaveStatus('idle');
      }, 2000);
    }, 500);
  };

  const handleReset = () => {
    setSettings(defaultSettings);
  };

  const handleExportData = () => {
    // 模拟数据导出
    const exportData = {
      timestamp: new Date().toISOString(),
      settings: settings,
      analysisHistory: [
        {
          stockCode: '000001',
          analysisDate: '2024-01-15',
          period: 30,
          similarityResults: [
            { similarity: 85.2, period: '2023-12-01 ~ 2023-12-31' },
            { similarity: 72.8, period: '2023-11-01 ~ 2023-11-30' }
          ]
        }
      ]
    };

    const dataStr = settings.exportFormat === 'json' 
      ? JSON.stringify(exportData, null, 2)
      : convertToCSV(exportData);
    
    const blob = new Blob([dataStr], { 
      type: settings.exportFormat === 'json' ? 'application/json' : 'text/csv' 
    });
    
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `stock_analysis_data.${settings.exportFormat}`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const convertToCSV = (data: any): string => {
    const headers = ['股票代码', '分析日期', '分析期间', '相似度', '对比期间'];
    const rows = [headers.join(',')];
    
    data.analysisHistory.forEach((item: any) => {
      item.similarityResults.forEach((result: any) => {
        rows.push([
          item.stockCode,
          item.analysisDate,
          item.period,
          result.similarity,
          result.period
        ].join(','));
      });
    });
    
    return rows.join('\n');
  };

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-4xl mx-auto">
        {/* 头部导航 */}
        <div className="bg-white rounded-lg shadow-sm p-4 mb-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <button
                onClick={() => navigate('/')}
                className="flex items-center gap-2 text-gray-600 hover:text-gray-800 transition-colors"
              >
                <ArrowLeft size={20} />
                返回首页
              </button>
              <div className="h-6 w-px bg-gray-300"></div>
              <div className="flex items-center gap-2">
                <SettingsIcon size={20} className="text-gray-600" />
                <h1 className="text-xl font-semibold text-gray-800">系统设置</h1>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={handleReset}
                className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-800 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                <RefreshCw size={16} />
                重置
              </button>
              <button
                onClick={handleSave}
                disabled={saveStatus === 'saving'}
                className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 text-white px-4 py-2 rounded-lg transition-colors"
              >
                {saveStatus === 'saving' ? (
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                ) : saveStatus === 'saved' ? (
                  '✓'
                ) : (
                  <Save size={16} />
                )}
                {saveStatus === 'saving' ? '保存中...' : saveStatus === 'saved' ? '已保存' : '保存设置'}
              </button>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 分析参数设置 */}
          <div className="bg-white rounded-lg shadow-sm p-6">
            <h2 className="text-lg font-semibold text-gray-800 mb-4">分析参数</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  默认相似度阈值 (%)
                </label>
                <input
                  type="number"
                  value={settings.similarityThreshold}
                  onChange={(e) => handleSettingChange('similarityThreshold', Number(e.target.value))}
                  min="0"
                  max="100"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <p className="mt-1 text-xs text-gray-500">
                  达到此阈值的相似走势将被特别标记
                </p>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  默认分析期间 (天)
                </label>
                <input
                  type="number"
                  value={settings.defaultAnalysisPeriod}
                  onChange={(e) => handleSettingChange('defaultAnalysisPeriod', Number(e.target.value))}
                  min="7"
                  max="365"
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                />
                <p className="mt-1 text-xs text-gray-500">
                  新建分析时的默认期间长度
                </p>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  数据保留期 (天)
                </label>
                <select
                  value={settings.dataRetention}
                  onChange={(e) => handleSettingChange('dataRetention', Number(e.target.value))}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value={30}>30天</option>
                  <option value={90}>90天</option>
                  <option value={180}>180天</option>
                  <option value={365}>1年</option>
                  <option value={730}>2年</option>
                </select>
                <p className="mt-1 text-xs text-gray-500">
                  超过此期间的分析记录将被自动清理
                </p>
              </div>
            </div>
          </div>

          {/* 界面设置 */}
          <div className="bg-white rounded-lg shadow-sm p-6">
            <h2 className="text-lg font-semibold text-gray-800 mb-4">界面设置</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  图表主题
                </label>
                <div className="flex gap-2">
                  <button
                    onClick={() => handleSettingChange('chartTheme', 'light')}
                    className={`px-4 py-2 rounded-lg border transition-colors ${
                      settings.chartTheme === 'light'
                        ? 'bg-blue-600 text-white border-blue-600'
                        : 'bg-white text-gray-700 border-gray-300 hover:border-blue-300'
                    }`}
                  >
                    浅色
                  </button>
                  <button
                    onClick={() => handleSettingChange('chartTheme', 'dark')}
                    className={`px-4 py-2 rounded-lg border transition-colors ${
                      settings.chartTheme === 'dark'
                        ? 'bg-blue-600 text-white border-blue-600'
                        : 'bg-white text-gray-700 border-gray-300 hover:border-blue-300'
                    }`}
                  >
                    深色
                  </button>
                </div>
              </div>
              
              <div>
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-gray-700">
                    自动刷新数据
                  </label>
                  <button
                    onClick={() => handleSettingChange('autoRefresh', !settings.autoRefresh)}
                    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                      settings.autoRefresh ? 'bg-blue-600' : 'bg-gray-200'
                    }`}
                  >
                    <span
                      className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                        settings.autoRefresh ? 'translate-x-6' : 'translate-x-1'
                      }`}
                    />
                  </button>
                </div>
                <p className="mt-1 text-xs text-gray-500">
                  启用后将定期自动更新股票数据
                </p>
              </div>
              
              {settings.autoRefresh && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    刷新间隔 (秒)
                  </label>
                  <select
                    value={settings.refreshInterval}
                    onChange={(e) => handleSettingChange('refreshInterval', Number(e.target.value))}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  >
                    <option value={30}>30秒</option>
                    <option value={60}>1分钟</option>
                    <option value={300}>5分钟</option>
                    <option value={600}>10分钟</option>
                  </select>
                </div>
              )}
            </div>
          </div>

          {/* 数据导出 */}
          <div className="bg-white rounded-lg shadow-sm p-6 lg:col-span-2">
            <h2 className="text-lg font-semibold text-gray-800 mb-4">数据导出</h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  导出格式
                </label>
                <select
                  value={settings.exportFormat}
                  onChange={(e) => handleSettingChange('exportFormat', e.target.value as 'csv' | 'json' | 'excel')}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                  <option value="csv">CSV 格式</option>
                  <option value="json">JSON 格式</option>
                  <option value="excel">Excel 格式</option>
                </select>
              </div>
              
              <div className="flex items-end">
                <button
                  onClick={handleExportData}
                  className="w-full bg-green-600 hover:bg-green-700 text-white font-medium py-2 px-4 rounded-lg transition-colors flex items-center justify-center gap-2"
                >
                  <Download size={16} />
                  导出分析数据
                </button>
              </div>
            </div>
            
            <div className="mt-4 p-4 bg-gray-50 rounded-lg">
              <h3 className="text-sm font-medium text-gray-800 mb-2">导出内容包括：</h3>
              <ul className="text-sm text-gray-600 space-y-1">
                <li>• 历史分析记录</li>
                <li>• 相似度计算结果</li>
                <li>• 系统配置参数</li>
                <li>• 股票代码和分析时间</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}